package com.nt.train.processor;
import com.nt.train.annotation.NTService;
import com.nt.train.annotation.PCS;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Component;
/**
 * @author hlf
 * @version 1.0
 * @date 2021/12/20 17:25
 */
@Component
public class PCSBeanFactoryPostProcessor implements BeanFactoryPostProcessor {

    public PCSBeanFactoryPostProcessor(){

    }

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        try {
            String[] pcsNames  =  beanFactory.getBeanNamesForAnnotation(PCS.class);
            for (int i = 0; i <pcsNames.length ; i++) {
                String pcsName = pcsNames[i] ;
                BeanDefinition definition = beanFactory.getBeanDefinition(pcsName);
                Class clazz  = Thread.currentThread().getContextClassLoader().loadClass(definition.getBeanClassName());
                PCS pcs =(PCS) AnnotationUtils.findAnnotation(clazz,PCS.class);
                System.out.println("自定义注解初始化："+pcs.id()+"_"+pcs.name());
                beanFactory.registerAlias(pcsName,pcs.id()+"_"+pcs.name());
            }

        }catch (Exception e){
            throw  new  RuntimeException(e);
        }
    }
}
